const request = require('../../utils/request'); // 引入封装好的请求工具

Page({
  data: {
    title: '若依管理系统', // 根据实际情况修改
    registerForm: {
      username: "",
      password: "",
      confirmPassword: "",
      code: "",
      uuid: ""
    },
    codeUrl: "",
    loading: false,
    captchaEnabled: true
  },

  onLoad() {
    this.getCode();
  },

  // 表单提交处理
  handleRegister(e) {
    const formData = e.detail.value;
    console.log('e',e.detail, this.data.registerForm.uuid);
    // 表单验证
    if (!this.validateForm(formData)) {
      return;
    }
    
    this.setData({ loading: true });
    
    // 模拟注册请求
    wx.request({
      url: 'http://localhost:8080/registerUser',
      method: 'POST',
      data: {
        username: formData.username,
        password: formData.password,
        code: formData.code,
        uuid: this.data.registerForm.uuid
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showModal({
            title: '系统提示',
            content: `恭喜你，您的账号 ${formData.username} 注册成功！`,
            showCancel: false,
            success: () => {
              wx.navigateTo({ url: '/pages/login/login' });
            }
          });
        } else {
          wx.showToast({ title: res.data.msg || '注册失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '请求失败，请重试', icon: 'none' });
      },
      complete: () => {
        this.setData({ loading: false });
        if (this.data.captchaEnabled) {
          this.getCode();
        }
      }
    });
  },

  // 表单验证
  validateForm(formData) {
    if (!formData.username || formData.username.length < 2 || formData.username.length > 20) {
      wx.showToast({ title: '用户账号长度必须介于2和20之间', icon: 'none' });
      return false;
    }
    
    if (!formData.password || formData.password.length < 5 || formData.password.length > 20) {
      wx.showToast({ title: '用户密码长度必须介于5和20之间', icon: 'none' });
      return false;
    }
    
    if (formData.password !== formData.confirmPassword) {
      wx.showToast({ title: '两次输入的密码不一致', icon: 'none' });
      return false;
    }
    
    if (this.data.captchaEnabled && !formData.code) {
      wx.showToast({ title: '请输入验证码', icon: 'none' });
      return false;
    }
    
    return true;
  },

  // 获取验证码图片
  getCode() {
    const url = '/captchaImage';
    request.get(url)
      .then(response => {
        console.log(response);
        this.setData({
          codeUrl: 'data:image/gif;base64,' + response.img,
          registerForm: {uuid: response.uuid}
        });
      })
      .catch(error => {
        console.error('获取验证码失败:', error);
      });
  },
});